package com.nuanshui.heatedloan.userinfo.service.thirdLogin;

import com.nuanshui.heatedloan.baseservice.service.CommonServiceImpl;
import com.nuanshui.framework.consts.TransactionManagerType;
import com.nuanshui.framework.exception.BizException;
import com.nuanshui.framework.exception.GlobalErrorCode;
import com.nuanshui.framework.utils.UniqueIdGenerator;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UserFansRelationMapper;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UserStateMapper;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UserWeixinAccountMapper;
import com.nuanshui.heatedloan.userinfo.dal.mapper.UsersMapper;
import com.nuanshui.heatedloan.userinfo.facade.UserAuthService;
import com.nuanshui.heatedloan.userinfo.facade.thirdlogin.ThirdUserService;
import com.nuanshui.heatedloan.userinfo.facade.wechat.WeChatService;
import com.nuanshui.heatedloan.userinfo.form.BoundUserForm;
import com.nuanshui.heatedloan.userinfo.model.ThirdUser;
import com.nuanshui.heatedloan.userinfo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * Created by zxh on 2017/2/10.
 */


public class BaseThirdUserServiceImpl extends CommonServiceImpl implements ThirdUserService {

    @Autowired
    protected UserFansRelationMapper userFansRelationMapper;

    @Autowired
    protected UsersMapper userMapper;

    @Autowired
    protected UserWeixinAccountMapper userWeixinAccountMapper;

    @Autowired
    protected WeChatService weChatService;

    @Autowired
    protected UserStateMapper userStateMapper;

    @Autowired
    UserAuthService userAuthService;

    @Transactional(readOnly=false,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    protected User saveUser(BoundUserForm boundUserForm) {
        User user = new User();
        user.setAdmin("1");
        user.setAvatar(boundUserForm.getImage());
        user.setCreatedAt(new Date());
        String nick = boundUserForm.getNickname();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(nick)){
            if(userStateMapper.userCountByNick(nick,null)>0) {
                boundUserForm.setNickname(GlobalParam.USER_DEFAULT_NICK+ UniqueIdGenerator.generateRandomNumStr(6));
            }
        }
        user.setNick(boundUserForm.getNickname());
        user.setLoginname(boundUserForm.getOpenid());
        user.setRecommended(true);
        user.setSignature(GlobalParam.USER_DEFAULT_SIGNATURE);
        userMapper.insert(user);

        userAuthService.loadUserAuth(user.getId());

        return user;
    }
    /**
     * 保存用户的默认操作
     */
    @Transactional(readOnly=false,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    private void saveUserDefaultOpt(User user) {
        userAuthService.loadUserAuth(user.getId());
    }

    @Override
    public User loadUser(String openId) {
        return null;
    }

    @Override
    public ThirdUser loadThirdUser(String userId) {
        return null;
    }

    @Override
    @Transactional(readOnly=false,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public User insertUser(BoundUserForm boundUserForm) {
        User user =  saveUser(boundUserForm);

        boundUserForm.setUserId(user.getId());

        insertThirdUser(boundUserForm);
        user.setIsNew(true);
        return user;
    }


    public void insertThirdUser(BoundUserForm boundUserForm) {

    }

    @Override
    @Transactional(readOnly=false,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public User authUser(BoundUserForm boundUserForm)
    {
        User user = null;
        synchronized (boundUserForm.getOpenid().intern()) {
            user = loadUser(boundUserForm.getOpenid());
            if (user == null) {// 表示第一次登陆，需要创建账号
                if (weChatService != null) {
                    boundUserForm = weChatService.uploadThirdUserHeadImg(boundUserForm);
                }

                user = insertUser(boundUserForm);
            }
        }

        return user;
    }

    protected String getExistUserError()
    {
        return "";
    }

    protected String getExistThirdUserError()
    {
        return "";
    }

    public void boundUser(BoundUserForm boundUserForm)
    {
        User oldUser = loadUser(boundUserForm.getOpenid());
        if(oldUser != null) {//表示qq账号已经 绑定一个用户，不能重复绑定
            throw new BizException(GlobalErrorCode.UNKNOWN, getExistUserError());
        }
        ThirdUser thirdUser = loadThirdUser(boundUserForm.getUserId());
        if(thirdUser != null) {//表示现在的账号已经被qq绑定 ，不能再绑定到别的 账号
            throw new BizException(GlobalErrorCode.UNKNOWN, getExistThirdUserError());
        }

        insertThirdUser(boundUserForm);
    }

    public int[] getMutexAccountTypes()
    {
        return null;
    }

    @Override
    @Transactional(readOnly=false,value=TransactionManagerType.USER_INFO_TRANSACTION_MANAGER)
    public void unBoundUser(String userId)
    {
        int[] mutexAccountTypes=getMutexAccountTypes();

        int nValid=mutexAccountTypes.length;
        int nCurrentValid=0;
        for (int type: mutexAccountTypes) {
            ThirdUser thirdUser = ThirdUserServiceUtil.GetThirdUserService(type).loadThirdUser(userId);
            if(thirdUser==null)
            {
                nCurrentValid++;
            }
        }

        User user = userMapper.selectByPrimaryKey(userId);
        if(nCurrentValid==nValid &&(user == null || StringUtils.isEmpty(user.getPhone()))) {
            //三个第三方账号都不存在 则不能解除手机号的绑定
            throw new BizException(GlobalErrorCode.UNKNOWN, "不能解除绑定");
        }
        deleteUser(userId);
    }

    /**
     * 删除三方账号
     * @param userId
     */
    public void deleteUser(String userId)
    {

    }

    @Override
    public void updateOpenId(String userId) {

    }

}
